<?php


namespace app\api\controller;

use app\api\model\Base as bs;
use think\Db;
use think\Request;

class User extends Base
{

    public function user()
    {
        $head = $this->request = Request::instance()->header();
        if(substr($head['token'], -1)>2){
            $this->apiReturn(101,'敢越过权限，你胆子蛮大嘛');
        }
        if (Request::instance()->method() == 'GET') {
            $page = input('current', '1', 'intval');
            $page_size = input('pageSize', 10, 'intval');
//            $data = Db::name('user')
//                ->alias('a')
//                ->join('user_class b','a.id = b.uid')
//                ->join('classgrade c','b.classgrade_id = c.id')
//                ->join('user_course d','a.id = d.uid')
//                ->join('course e','d.course_id = e.id')->field(['e.id'=>'course_id'])
//                ->field('a.username,a.mobile,a.permissions,a.student_number,e.course_name')
//                ->field(['a.id'=>'key','c.id'=>'classgrade_id','c.name'=>'classgrade_name','e.id'=>'course_id'])
//                ->where('a.status',1)
//                ->page($page,$page_size)
//                ->select();
            $like = I('username|course|student_number|permissions|class_name');
            switch ($like['permissions']){
                case '超级管理员':
                    $like['permissions'] = 1;
                    break;
                case '管理员':
                    $like['permissions'] = 2;
                    break;
                case '老师':
                    $like['permissions'] = 3;
                    break;
                case '学生':
                    $like['permissions'] = 4;
                    break;
            }
            $data = Db::name('user')
                ->alias('a')
                ->field('a.username,a.mobile,a.permissions,a.student_number')
                ->join('user_class b', 'b.uid = a.id')
                ->join('classgrade c', 'b.classgrade_id = c.id')
                ->field(['c.id' => 'class_id', 'c.name' => 'class_name'])
                ->where('a.status', 1)
                ->field(['a.id' => 'key'])
                ->where('username', 'like', '%' . $like['username'] . '%')
                ->where('student_number', 'like', '%' . $like['student_number'] . '%')
                ->where('permissions', 'like', '%' . $like['permissions'] . '%')
                ->where('c.name', 'like', '%' . $like['class_name'] . '%')
                ->page($page, $page_size)
                ->order('permissions asc')
                ->order('a.id asc');
            if ($like['course'] != null) {
                $data->join('user_course d', 'd.uid = a.id')
                    ->join('course e', 'd.course_id = e.id')
                    ->where('e.course_name', 'like', '%' . $like['course'] . '%');
            }
            $data = $data->select();

            $newData = [];
            foreach ($data as $k => &$v) {
                $id = $v['key'];
                $course = Db::name('user_course')
                    ->alias('a')
                    ->where('a.uid =' . $id)
                    ->join('course b', 'a.course_id = b.id')
                    ->field(['b.id' => 'course_id', 'b.course_name' => 'course_name'])
                    ->where('a.status', 1)
                    ->where('b.status', 1)
                    ->select();


                if (count($course) == 0) {
                    $course = [[
                        'course_id' => null,
                        'course_name' => null,
                    ]];
                }
                array_push($newData, [
                    "username" => $v["username"],
                    "student_number" => $v["student_number"],
                    "permissions" => $v["permissions"],
                    "class_name" => $v["class_name"],
                    "key" => $v["key"],
                    "class_id" => $v["class_id"],
                    "course" => $course
                ]);
            }
            //我写的转换数据方法
//            dump($data);
//            for($i = 0 ; $i<count($data,0);$i++){
//                for($j = 0 ; $j < $i;$j++){
//                    if($data[$i]['username'] == $data[$j]['username']){
//                        $currCourse = [
//                            "course_id"=> $data[$j]['course_id'],
//                            "course_name"=> $data[$j]['course_name'],
//                        ];
//                        if(array_key_exists('course',$data[$i])){
//                            array_push($data[$i]['course'],$currCourse);
//                        }else{
//                            $data[$i]['course'] = $currCourse;
//                        }
//                    }
//                }
//            }

            //我写的转换数据方法
//            for($i = 0 ; $i<count($data,0);$i++){
//                for($j = 0 ; $j < $i;$j++){
//                    if($data[$i]['username'] == $data[$j]['username']){
//                        $currCourse = [
//                            "course_id"=> $data[$j]['course_id'],
//                            "course_name"=> $data[$j]['course_name'],
//                        ];
//                        if(array_key_exists('course',$data[$i])){
//                            array_push($data[$i]['course'],$currCourse);
//                            unset($data[$j]);
//                        }else{
//                            $data[$i]['course'] = $currCourse;
//                        }
//                    }
//                }
//            }

            //万平朋友写的转换数据方法
//            $newData = [];
//            for ($i = 0; $i < count($data); $i++) {
//                $currentUserName = $data[$i]["username"];
//                $studentNumber = $data[$i]["student_number"];
//                $permissions = $data[$i]["permissions"];
//                $className = $data[$i]["classgrade_name"];
//                $thisCourse = [
//                    "course_id"=>$data[$i]["course_id"],
//                    "course_name"=>$data[$i]["course_name"]
//                ];
//                $inNewData = "N";
//                for($j = 0; $j < count($newData); $j++){
//                    if($newData[$j]["username"] == $currentUserName){
//                        array_push($newData[$j]["course"],$thisCourse);
//                        $inNewData = "Y";
//                        break;
//                    }
//                }
//                if($inNewData == "N"){
//                    array_push($newData,[
//                        "username"=>$currentUserName,
//                        "student_number"=>$studentNumber,
//                        "permissions"=>$permissions,
//                        "class_name"=>$className,
//                        "key"=>$data[$i]["key"],
//                        "course"=>[
//                            $thisCourse
//                        ]
//                    ]);
//                }
//            }
            //不显示超级管理员
//            $data = array_splice($newData,1);
            $total = bs::total('user', 'status = 1');
            $this->apiReturn(200, '', $newData, $total);
        }

        if (Request::instance()->method() == 'POST') {
            $value = I('username|permissions|class_id|student_number');
            foreach ($value as $k => $v) {
                if (!$v) {
                    $this->apiReturn(303, 'lack ' . $k);
                }
            }
            $value['create_time'] = time();
            $value['update_time'] = time();
//            $value['password'] = user_md5($value['password']);
            $value['password'] = user_md5('123456');
            $class_id = $value['class_id'];
            unset($value['class_id']);
            Db::startTrans();
            try {
                $id = bs::add('user', $value);
                $user_class = bs::add('user_class', ['uid' => $id, 'classgrade_id' => $class_id]);
                if ($id && $user_class) {
                    Db::commit();
                    $this->apiReturn(200, '', ['id' => $id]);
                    return true;
                }
            } catch (Exception $e) {
                Db::rollback();
                return $e->getMessage();
            }
            $this->apiReturn(200, '', ['id' => $id]);
        }
        if (Request::instance()->method() == 'PUT') {
            $value = I('id|username|permissions|class_id|student_number');
            foreach ($value as $k => $v) {
                if (!$v) {
                    $this->apiReturn(303, 'lack ' . $k);
                }
            }
            $value['update_time'] = time();
            Db::startTrans();
            try {
                $userInfoEditFlag = bs::edit('user', $value['id'], [
                    'id' => $value['id'],
                    'username' => $value['username'],
                    'permissions' => $value['permissions'],
                    'student_number' => $value['student_number'],
                ]);
                $userClassEditFlag = Db::name('user_class')->where(['uid' => $value['id']])->update([
                    'classgrade_id' => $value['class_id'],
                ]);
                if ($userInfoEditFlag || $userClassEditFlag) {
                    Db::commit();
                    $this->apiReturn(200, '', ['success' => 'ok']);
                    return true;
                } else {
                    return false;
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->apiReturn(200, '', ['success' => 'fail']);
            }
        }
        if (Request::instance()->method() == 'DELETE') {
            $id = input('id');
            if (!$id) {
                $this->apiReturn(303, 'lack id');
            }
            $return_key = bs::del('user', $id);
            $this->apiReturn(200, '', $return_key);
        }
    }

}